<?php
/*******************************************************************************
 * $Date:: Jan 24, 2011 3:26:01 PM                                              $
 * $Revision:                                                                  $
 * $Author:: Tuan Duong                                                        $
 * $Comment::                                                                  $
 ******************************************************************************/ 
/**
 * Description here...
 * 
 * @package Lua
 * @subpackage Form
 * @author Tuan Duong <bacduong[at]gmail[dot]com>
 * @version 
 */

class Lua_Form_Abstract extends Zend_Form
{
    public function init()
    {
        $this->setElementDecorators(array(
            new Lua_Form_ElementDecorator()
        ));
        $this->setDisableLoadDefaultDecorators(true);
        $this->addDecorator('FormElements')
             ->addDecorator(array('Buttons' => new Lua_Form_ButtonsDecorator()))
             ->addDecorator('Form');
    }
    
    public function addElement($element, $name = null, $options = null)
    {
        if ($element instanceof Zend_Form_Element) {
            if ($element->getLabel() == null) {
                $element->setLabel($this->getLabelForName($element->getName()));
            }
        } elseif (is_string($element)) {
            if (!isset($options['label'])) {
                $options['label'] = $this->getLabelForName($name);
            }
        }
        parent::addElement($element, $name, $options);
    }

    private function getLabelForName($name)
    {
        if (substr($name, strlen($name) - 3) == '_id') {
            $name = substr($name, strlen($name) - 3);
        }
        return ucfirst(str_replace('_', ' ', $name));
    }

    /**
     * @param array $errors
     */
    public function addElementErrors(array $errors)
    {
        foreach ($errors as $name => $messages) {
            $element = $this->getElement($name);
            if ($element != null) {
                if (is_string($messages)) $messages = array($messages);
                if (is_array($messages)) {
                    foreach ($messages as $message) {
                        $element->addError($message);
                    }
                }
            }
        }
    }

    /**
     * @var string
     */
    protected $resetUrl;
    
    public function setResetUrl($resetUrl)
    {
        $this->resetUrl = $resetUrl;
        $formDecorator = $this->getDecorator('Form');
        if ($formDecorator) {
            $formDecorator->setOption('data-reset-url', $resetUrl);
        }
    }

    public function getResetUrl()
    {
        return $this->resetUrl;
    }
}